import fs from 'fs';
import path from 'path';

// Define the paths of the files we need to swap
const mainFiles = {
  old: 'src/main.ts',
  new: 'src/NewMain.ts'
};

const appFiles = {
  old: 'src/App.vue',
  new: 'src/NewApp.vue'
};

const indexFiles = {
  old: 'index.html',
  new: 'NewIndex.html'
};

// Function to read file content
function readFile(filePath) {
  return fs.readFileSync(filePath, 'utf8');
}

// Function to write content to a file
function writeFile(filePath, content) {
  fs.writeFileSync(filePath, content, 'utf8');
}

// Main function to switch versions
function switchVersion(useNew = true) {
  try {
    // Switch main.ts
    const mainContent = readFile(useNew ? mainFiles.new : mainFiles.old);
    writeFile('src/main.ts', mainContent);
    console.log(`Updated src/main.ts to use ${useNew ? 'new' : 'old'} version`);

    // Switch index.html
    const indexContent = readFile(useNew ? indexFiles.new : indexFiles.old);
    writeFile('index.html', indexContent);
    console.log(`Updated index.html to use ${useNew ? 'new' : 'old'} version`);

    // Backup and restore components
    if (useNew) {
      // Backup old App.vue if not already backed up
      if (!fs.existsSync('src/App.vue.bak')) {
        const oldAppContent = readFile(appFiles.old);
        writeFile('src/App.vue.bak', oldAppContent);
        console.log('Backed up original App.vue to App.vue.bak');
      }

      // Set App.vue to NewApp.vue content
      const newAppContent = readFile(appFiles.new);
      writeFile('src/App.vue', newAppContent);
      console.log('Updated App.vue to use new version');
    } else {
      // Restore original App.vue
      if (fs.existsSync('src/App.vue.bak')) {
        const backupContent = readFile('src/App.vue.bak');
        writeFile('src/App.vue', backupContent);
        console.log('Restored original App.vue from backup');
      } else {
        console.warn('Warning: No backup of App.vue found, leaving as is');
      }
    }

    console.log(`Successfully switched to ${useNew ? 'new' : 'old'} version`);
  } catch (error) {
    console.error('Error switching versions:', error);
  }
}

// Parse command line arguments
const args = process.argv.slice(2);
if (args.length === 0 || args[0] === 'new') {
  switchVersion(true);
} else if (args[0] === 'old') {
  switchVersion(false);
} else {
  console.log('Usage: node switch-versions.js [new|old]');
  console.log('  "new" - Switch to the new version (default)');
  console.log('  "old" - Switch back to the original version');
}